Создание чрезвычайно простой программы, в которой кнопка следует за мышью и при нажатии изменяет размер случайным образом. Но когда я запускаю приведенный ниже код, я получаю сообщение об ошибке, в котором говорится, что свойство «высота» неизвестно. Код:
import tkinter as tk
from tkinter import ttk
import random
window = tk.Tk()
def moved(e):
myx = e.x
myy = e.y
mylbl.place(x=myx - 20, y=myy - 20)
def randomsize():
size = random.randrange(20, 200)
sizey = size * 2
mylbl.config(width= sizey, height = size)
mylbl = ttk.Button(window, text = "Hello", command=randomsize, height=30, width = 60)
mylbl.place(x=10, y=10)
window.bind("<Motion>", moved)
window.mainloop()
Ошибка:
in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-height"
Я думаю, что в ttk
настроить высоту и ширину напрямую невозможно. (Но в tkinter.Button
это возможно).
Итак, чтобы настроить новую высоту в ttk
, нам нужно изменить размер шрифта и отступы. Это нужно сделать, используя метод ttk.Style
.
import tkinter as tk
from tkinter import ttk
import random
# An empty dict is declared as I want to avoid some global variables
dct = {}
def moved(e):
# As e.x and e.y are optional global variables, I've declared them as values of dct
dct['myx'] = e.x
dct['myy'] = e.y
# Remove the originally placed position
dct['mylbl'].place_forget()
# Place in new position
dct['mylbl'].place(x= dct['myx'] - 20, y= dct['myy'] - 20)
def randomsize():
# As the button's height changes with font size and padding, we get random values for font_size and padding
x_pad = random.randrange(5, 40)
y_pad = x_pad * 2
fnt_size = random.randrange(8, 25)
# If previous font_size & new font_size are same, create another font_size
fnt_size = random.randrange(8, 25) if fnt_size == fnt_size else fnt_size
# Hide the previousely placed position
dct['mylbl'].place_forget()
# Configure new style to the button with new font size and padding
dct['stl'].configure('TButton', font = ('Helvetica', fnt_size), padding = (x_pad, y_pad))
# Apply the new style
dct['mylbl'] = ttk.Button(window, text = "Hello", command=randomsize, style = 'TButton')
# I haven't changed the position. But If you want to place the button to the moved position, change x = dct['myx'] and y = dct['myy']
dct['mylbl'].place(x=10, y=10)
window = tk.Tk()
# Add geometry
window.geometry('400x300')
# To avoid using global variable, Style is made as a value of the dict
dct['stl'] = ttk.Style()
dct['stl'].configure('TLabel', font=('Helvetica', 12), padding=5)
# To avoid using global variable, Button is made as a value of the dict
dct['mylbl'] = ttk.Button(window, text = "Hello", command=randomsize, style = 'TButton')
dct['mylbl'].place(x=10, y=10)
window.bind("<Motion>", moved)
window.mainloop()
Виджеты Ttk обычно не настраиваются с помощью параметров ключевых слов, передаваемых их конструктору или методу
.configure()
, вам необходимо использовать объекты TtkStyle
. Самым простым решением было бы использовать здесь обычный виджетtk.Button
, а не версию ttk.