【问题标题】:How to place items/ widgets inside other classes using tkinter and python oop如何使用 tkinter 和 python oop 将项目/小部件放置在其他类中
【发布时间】:2019-03-26 00:11:56
【问题描述】:

我正在努力寻找一种方法来在每个按钮下方添加一个彩色框,具体取决于单击哪个按钮。使用 tkinter 和 python3,我想使用类在按钮 1 下添加一个红色框(如果单击),或者在按钮 2 下添加一个绿色框(如果单击)。我还希望它位于每个按钮所在的相应框架内。我在这里有什么选择?感谢任何支持:)

import tkinter as tk

class MyDialog:
    def __init__(self, parent):
        top = self.top = tk.Toplevel(parent)
    self.myLabel = tk.Label(top, text='Enter Name')
        self.myLabel.pack()

        self.myEntryBox = tk.Entry(top)
        self.myEntryBox.pack()

        self.mySubmitButton = tk.Button(top, text='Press', command=self.send)
        self.mySubmitButton.pack()

    def send(self):
        global username
        username = self.myEntryBox.get()
        self.top.destroy()

def onClick():
    inputDialog = MyDialog(root)
    root.wait_window(inputDialog.top)
    print('Username: ', username)

class MainWindow:

    def __init__(self, master):

        mainLabel = tk.Label(root, text='Main Window')
        mainLabel.pack()

        button1_frame = tk.Frame()
        button1_frame.pack()

        mainButton = tk.Button(root, text='Button 1', command=onClick, width=20)
        mainButton.pack(side=tk.LEFT)

        button_frame2 = tk.Frame()
        button_frame2.pack()

        mainButton2 = tk.Button(root, text='Button 2', command=onClick, width=20)
        mainButton2.pack(side=tk.LEFT)


root = tk.Tk()
app = MainWindow(root)
root.mainloop()

【问题讨论】:

    标签: python python-3.x user-interface tkinter


    【解决方案1】:

    关于你的问题有很多不清楚的地方,但希望我明白你想要什么:

    1. 您想用颜色指示单击了哪个按钮。

    你应该给按钮绑定一个事件,并使用config方法改变背景颜色。

    1. 您希望按钮位于您创建的框架内,而不是根窗口本身。

    您已经初始化了框架,但是您没有为框架设置父级,也没有将框架用作按钮的父级。

    所以你可能想修改你的代码更像:

    class MainWindow:
    
    def __init__(self, master):
    
        mainLabel = tk.Label(root, text='Main Window')
        mainLabel.pack()
    
        button1_frame = tk.Frame(root)
        button1_frame.pack()
    
        mainButton = tk.Button(button1_frame, text='Button 1', command=onClick, width=20)
        mainButton.bind('<Button-1>', lambda event: mainButton.config(bg='red'))
        mainButton.pack(side=tk.LEFT)
    
        button_frame2 = tk.Frame(root)
        button_frame2.pack()
    
        mainButton2 = tk.Button(button_frame2, text='Button 2', command=onClick, width=20)
        mainButton2.bind('<Button-1>', lambda event: mainButton2.config(bg='green'))
        mainButton2.pack(side=tk.LEFT)
    

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2018-11-23
      相关资源
      最近更新 更多