我一直在尝试在 python 中使用 Tkinter 创建一个“骰子模拟器”,但是当我尝试将“文本”小部件放置在其框架内时,它保持固定在框架的左上角。我尝试过网格、移动和放置功能,但都不起作用。这是我的代码:
from tkinter import *
from random import *
def roll():
txt.delete(0.0, END)
txt.insert(END, str(randint(1,6)))
window = Tk()
window.title('Dice simulator')
canvas = Canvas(window, width=800, height=500, bg='brown')
canvas.pack()
dice = canvas.create_rectangle(375, 225, 425, 275, fill='white')
frame = Frame(canvas, width=25, height=15)
window = canvas.create_window(400, 295, window=frame)
txtframe = Frame(canvas, width=50, height=50)
txtwindow = canvas.create_window(400, 250, window=txtframe, width=49, height=49)
txt = Text(txtframe, font=50)
button = Button(frame, text='Roll', command=roll)
button.pack()
txt.pack()
您有什么建议?帮助将不胜感激。
上面给出的详细信息,在这个网站上并不令人惊奇。刚刚开始。
可以使用包参数
expand
和 fill
: 使内容在框架中居中
widget.pack(expand=True, fill='both')
要防止框架根据内容调整其大小,您可以使用
pack_propatage
方法。
widget.pack_propagate(False)
我使用
Label
而不是 Text
小部件重写了您的代码,并重新排列了它以获得更好的可读性:
from tkinter import *
from random import *
def roll():
dice_txt.config(text=str(randint(1,6)))
window = Tk()
window.title('Dice simulator')
canvas = Canvas(window, width=800, height=500, bg='brown')
canvas.pack()
# Dice
dice = canvas.create_rectangle(375, 225, 425, 275, fill='white')
txtframe = Frame(canvas, width=50, height=50)
# Keep txtframe from changing size when dice_txt does
txtframe.pack_propagate(False)
dice_txt = Label(txtframe, font=50)
# Put the dice_text in te center of txtframe
dice_txt.pack(expand=True, fill='both')
txtwindow = canvas.create_window(400, 250, window=txtframe, width=49, height=49)
# Roll button
frame = Frame(canvas, width=25, height=15)
window = canvas.create_window(400, 295, window=frame)
button = Button(frame, text='Roll', command=roll)
button.pack()
对于简单的骰子模拟器,您不需要那些框架和文本小部件,只需使用
.create_text()
来显示生成的骰子数字:
import random
import tkinter as tk
def roll():
canvas.itemconfig(dice, text=random.randint(1, 6))
window = tk.Tk()
window.title("Dice Simulator")
canvas = tk.Canvas(window, width=800, height=500, bg="brown")
canvas.pack()
canvas.create_rectangle(375, 225, 425, 275, fill="white")
dice = canvas.create_text(400, 250, font=('', 40))
button = tk.Button(canvas, text="Roll", width=5, command=roll)
canvas.create_window(400, 295, window=button)
window.mainloop()
结果: