我试图通过一个按钮在Python中重新加载Tkinter窗口,但我很难搞清楚它。你看,它使用$("#bb").change(function() {
console.log("change in bb");
$("#candidateTextArea").prop("disabled",false);
}
);
并从列表中随机生成单词,当你点击按钮时,我想把标签设置为不同的单词,几乎就像滚动骰子但是用单词。
import random
感谢您的帮助:)
答案 0 :(得分:0)
Canvas有方法itemconfig(item_id, option=new_value)
来更改项目选项。即
canvas.itemconfig(creature_text, text=random.choice(creature))
简单,有效的例子
try:
from Tkinter import * # Python 2
except:
from tkinter import * # Python 3
import random
# --- functions ---
def change_creature():
# change text in item
canvas.itemconfig(creature_text, text=random.choice(creature))
# --- data ---
creature = [
'is an Animal', 'is a Human', 'is an Artificial Intelligence',
'is an Alien', 'is a Mage','is a Reptillian','is a Shapeshifter',
'is Undead', 'is a Scorpion Hedgehog', 'is an Angel', 'is a Demon'
]
# --- main ---
root = Tk()
canvas = Canvas(root, height=100, width=300)
canvas.grid()
# create empty item
creature_text = canvas.create_text(10, 10, anchor='nw')
# generate first text in item
change_creature()
# use button to call the same function
button = Button(root, text='Generate Creature', command=change_creature)
button.grid()
root.mainloop()
编辑:更通用 - 使用功能
中的参数change_text(creature_text_1, creature)
command=lambda:change_text(creature_text_1, creature))
或直接使用它(没有自己的功能)
canvas.itemconfig(creature_text_1, text=random.choice(creature))
command=lambda:canvas.itemconfig(creature_text_1, text=random.choice(creature))
代码:
try:
from Tkinter import * # Python 2
except:
from tkinter import * # Python 3
import random
# --- functions ---
def change_text(item_id, all_text):
# change text in item
canvas.itemconfig(item_id, text=random.choice(all_text))
# --- data ---
creature = [
'is an Animal', 'is a Human', 'is an Artificial Intelligence',
'is an Alien', 'is a Mage','is a Reptillian','is a Shapeshifter',
'is Undead', 'is a Scorpion Hedgehog', 'is an Angel', 'is a Demon'
]
# --- main ---
root = Tk()
canvas = Canvas(root, height=100, width=300)
canvas.grid()
# create empty items
creature_text_1 = canvas.create_text(10, 10, anchor='nw')
creature_text_2 = canvas.create_text(10, 30, anchor='nw')
# generate first text in item
change_text(creature_text_1, creature)
# or directly
canvas.itemconfig(creature_text_2, text=random.choice(creature))
# use buttons to call the same function
button = Button(root, text='Generate Creature 1', command=lambda:change_text(creature_text_1, creature))
button.grid()
# or directly
button = Button(root, text='Generate Creature 2', command=lambda:canvas.itemconfig(creature_text_2, text=random.choice(creature)))
button.grid()
root.mainloop()