【发布时间】:2019-07-25 22:25:46
【问题描述】:
我正在尝试构建一个简单的 tkinter UI,它既显示简单 RPG 角色的属性,又允许玩家为自制 RPG 更新这些属性。我已经回答了很多类似问题的答案,但我遗漏了一些东西(可能很明显),而且我的按钮不会改变 UI。
我正在做这个小项目,作为完成 python 速成课程的后续项目(这真的很有帮助),但这个项目让我很难过。
我已经在一个单独的脚本中测试了这些函数并按照我的意愿进行操作,但是当我尝试让它们在 UI 中工作时,什么也没有发生,没有错误或回溯,也没有对 UI 进行任何更改。
很抱歉,我认为本示例中较长行中的某些缩进可能是错误的,但我保证它在实际脚本中是好的。我制作了一个名为 character 的单独模块,其中包含 Character 类和相关的函数。正如我上面所说,当我只运行该脚本时它们可以正常工作,但它们不会影响 UI(即使它们可以正常导入并且不会导致任何错误)。
from tkinter import LEFT, RIGHT, CENTER, X, Y, SUNKEN
import tkinter as tk
from character import Character
class GlobalFrequency:
"""The overall class for the app"""
def __init__(self, master):
"""intialise the attributes of the variable"""
self.master = master
master.title = "Global Frequency"
#trying to set this up with a character
self.character = Character('Miranda zero')
self.name_label = tk.Label(master, text =
self.character.name.title(),
font=("Helvetica", 20))
self.name_label.pack()
#This is where the buttons and stuff start,
self.str_frame = tk.Frame(master, width=400)#strength frame
self.str_frame.pack(fill=X)
#This is the only button with a function so far
self.st_btn_1 = tk.Button(self.str_frame, text = 'Strength
up', font=("System", 16),
command = lambda:
self.character.increase_attribute('strength'))
self.st_btn_1.pack(side = LEFT)
#This is a second button, not assigned a function yet
self.st_btn_2 = tk.Button(self.str_frame, text = 'Strength
down', font=("System", 16))
self.st_btn_2.pack(side = LEFT)
self.str_label = tk.Label(self.str_frame)
self.str_label.configure(
text=self.character.attributes['Strength'],
font=("System", 16))
self.str_label.pack()
root = tk.Tk()
root.geometry("400x600")
gui = GlobalFrequency(root)
root.mainloop()
当 self.st_btn_1 被按下时应该发生的是它旁边的标签应该更新为:
Strenght: 2
正如我所说,当我只是在 tkinter 代码之外运行该函数时,字符属性确实会更新,但它不会影响 UI。
如果这个问题真的很愚蠢,或者我的代码是粗制滥造的,我很抱歉,但我正在尝试边做边学。
提前感谢您提供的任何帮助。
【问题讨论】:
标签: python-3.x button tkinter