【发布时间】:2018-08-09 14:59:11
【问题描述】:
我在用 Python 编码时遇到了一个我找不到解决方案的问题。我有一个 tkinter 网格,它会自动调整大小以适应它所在的窗口大小,但我希望按钮/标签中的文本也能调整大小以适应新网格。一个基本的例子如下:
from tkinter import *
root = Tk()
for x in range(3):
for y in range(3):
Label(root, width = 2, height = 4, text = (y * 3 + x) + 1, relief = GROOVE).grid(row = y, column = x, sticky = N+E+S+W)
Grid.rowconfigure(root, y, weight = 1)
Grid.columnconfigure(root, x, weight = 1)
root.mainloop()
我希望文本在您拖动窗口以展开它时增加。如何做到这一点?
编辑:
Mike - SMT 的解决方案效果很好,但不适用于我在他的回复评论中描述的情况。
这是我的代码:
from tkinter import *
import tkinter.font as tkFont
grey = [0,1,2,6,7,8,9,10,11,15,16,17,18,19,20,24,25,26,30,31,32,39,40,41,48,49,50,54,55,56,60,61,62,63,64,65,69,70,71,72,73,74,78,79,80]
btn_list = []
filled = []
filled_ID = []
class GUI(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.screen_init()
self.key = None
self.keydetection = False
self.detect()
self.bind_all("<Key>", self.key_event)
def screen_init(self, master = None):
for x in range(9):
for y in range(9):
btn_list.append(Button(master, width = 40, height = 40, image = pixel, compound = CENTER, bg = "#D3D3D3" if 9 * y + x in grey else "#FFFFFF", command = lambda c = 9 * y + x: self.click(c)))
btn_list[-1].grid(row = y, column = x, sticky = N+E+S+W)
Grid.rowconfigure(root, y, weight = 1)
Grid.columnconfigure(root, x, weight = 1)
def update(self, btn_ID, number = None, colour = "#000000", master = None):
y = btn_ID // 9
x = btn_ID % 9
Button(master, width = 40, height = 40, image = pixel, text = number, compound = CENTER, fg = colour, bg = "#D3D3D3" if 9 * y + x in grey else "#FFFFFF", command = lambda c = 9 * y + x: self.click(c)).grid(row = y, column = x, sticky = N+E+S+W)
def detect(self):
self.keydetection = not self.keydetection
def key_event(self, event):
try:
self.key = int(event.keysym)
except:
print("Numbers Only!")
def click(self, btn_ID):
if btn_ID in filled:
filled_ID.pop(filled.index(btn_ID))
filled.remove(btn_ID)
window.update(btn_ID)
else:
filled.append(btn_ID)
filled_ID.append(self.key)
window.update(btn_ID, self.key)
def font_resize(event=None):
for btn in btn_list:
x = btn.winfo_width()
y = btn.winfo_height()
if x < y:
btn.config(font=("Courier", (x-10)))
else:
btn.config(font=("Courier", (y-10)))
if __name__ == '__main__':
root = Tk()
root.title("Example")
pixel = PhotoImage(width = 1, height = 1)
font = tkFont.Font(family = "Helvetica")
window = GUI(root)
root.bind("<Configure>", font_resize)
root.mainloop()
这意味着当代码最初运行时文本不在网格中,因为用户按下数字键选择一个数字,然后单击他们希望该数字出现在网格中的位置,这似乎break Mike - SMT 的解决方案。有什么修复吗?
【问题讨论】:
-
我猜你可以将窗口配置事件绑定到一个计算按钮大小的函数,然后动态调整字体。
-
本网站上有几个与标签增大或缩小时更改字体大小有关的问题。你在问之前搜索过它们吗?例如,Python3: How to dynamically resize button text in tkinter/ttk? 或 Python/Tkinter: expanding fontsize dynamically to fill frame
标签: python python-3.x tkinter