ytac=[]
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.style = ttk.Style(self)
self.style.theme_use("classic")
self.frame0 = ttk.Frame(self, padding=(5,5))
self.frame1 = ttk.Frame(self, padding=(5,5))
self.frame2 = ttk.Frame(self, padding=(5,5))
self.frame3 = ttk.Frame(self, padding=(5,5))
self.initialize_frames()
self.initialize_widgets()
self.geometry("450x400")
def initialize_widgets(self):
self.uno_label.grid(row=0, column=0, sticky=tk.NSEW, padx=10, pady=10, columnspan=10)
def make_frame0(self):
self.coding_button = ttk.Button(self.frame0, text="Coding", command=self.get)
self.coding_button.grid(row=1, column=5)
def make_frame1(self):
self.gamedev_button = ttk.Button(self.frame1, text="Game Development", command=self.get)
self.gamedev_button.grid(row=1 ,column=5)
def make_frame2(self):
self.digitalmedia_button = ttk.Button(self.frame2, text="Digital Media", command=self.get)
self.digitalmedia_button.grid(row=1, column=5)
def make_frame3(self):
self.uno_label = ttk.Label(self, text="Hello fellow Ytacer or so they call 'it. Ytac is a 4 week journey that allows to \ntake a Stem class of your choosing from a not so wide range of classes. \nIt's also unfourtenetly not sponsored by Dr.Pepper(f in the chat). 'Are you ready \nto start your expedition? What's 'my name you 'ask? I have 'no name but you \ncan call me Took. 'And also, Mel 'sucks and 'shouldn't be 'appreciated \nthroughout the rest of the cohort. *ahem*, they're 3 pathways to choose from,\n Coding(1), Game Development(2), Digital Media(3). Choose from one of these \nby clicking on the respective button. But before you do that I would like for us \nto introduce our sponsors RAID SHADOW LEGE-.")
def initialize_frames(self):
self.make_frame0()
self.make_frame1()
self.make_frame2()
self.make_frame3()
self.frame0.grid(row=4, column=0)
self.frame1.grid(row=4, column=1)
self.frame2.grid(row=4, column=2)
def get(self):
if self.coding_button:
print("ok")
elif self.gamedev_button:
print("poyo")
elif self.digitalmedia_button:
print("GUH-HUH")
if __name__ == "__main__":
app = App("YTAC")
app.mainloop()这个def函数将只打印出第一个字符串,而不是其他两个,即使我按下了所有相应的按钮。

期望对应的字符串在我按下相应的按钮后打印出来。我试图将私生子改成自己的if语句,但这导致了更多的问题。
发布于 2022-10-30 04:02:46
如果没有看到所有的代码,我就无法准确地诊断您的问题,但它可能在于您如何使用Tkinter按钮。
另一个似乎与你的To Detect Button Press In Python Tkinter Module相似的问题
关于Tkinter按钮的非常全面的教程:https://www.tutorialspoint.com/python/tk_button.htm
本质上,Tkinter按钮的定义如下:
buttonName = tkinter.Button(master, option1=value1, option2=value1...)Tkinter按钮没有“按下”变量,相反,您可以设置在按下按钮时运行的命令(函数)。
buttonName = tkinter.Button(master, command=function_name, option1=value1, option2=value2...)注意:不要在函数名后面加上括号,因为那样会运行函数。唯一的例外是,如果有一个返回函数的函数
如果您想要在按下按钮时更改的全局变量,则类似于这样的函数可以工作:
global_var = False
def callback():
global global_var
global_var = not global_var
button = tkinter.Button(master, command=callback)在上面的示例中,将master替换为Tkinter窗口的名称。
https://stackoverflow.com/questions/74250363
复制相似问题