帧在Tkinter中是否有单独的帧位置?

时间:2018-08-09 15:40:33

标签: python python-3.x layout tkinter

我遇到了一个问题,我以为我知道答案。很奇怪,我做了一个框架来放入条目和按钮,这样它们就不会由于我制作的盒子而相距太远。但是,条目和按钮不在框架中,因为框架的背景是红色,但是红色没有出现,并且条目/按钮仍然很奇怪地分开。

代码:

# Hex GUI
import re
import tkinter as tk

hexa_checker_regex = re.compile(r'^#')


class Window:


    def __init__(self, master, error_checker):
        self.error_checker = error_checker
        self.master = master
        self.master.configure(bg='LightBlue')
        self.set_up()


    def set_up(self):

        # =====FRAME FOR ENTRYS + BUTTONS=====

        self.enter_frame = tk.Frame(self.master, bg='Red').grid(row=0, column=2, sticky='n')

        # =====COLOR BOX=====

        self.color = tk.Frame(self.master, highlightbackground='Black', height=100, width=100, highlightthickness=5)
        self.color.grid(row=0, column=0)

        # =====SEPERATOR=====

        tk.Frame(self.master, width=200, bg='LightBlue').grid(row=0, column=1)


        # =====HEXADECIMAL COLORS=====

        tk.Label(self.enter_frame, text='Hex:', bg='LightBlue').grid(row=0, column=2, sticky='n')

        self.the_color_hex = tk.Entry(self.enter_frame, width=50)
        self.the_color_hex.grid(row=0, column=3, sticky='n')

        tk.Button(self.enter_frame, text='Change Color', command=self.change_color_hex).grid(row=0, column=4, sticky='n')

        # =====HEX ERROR=====

        tk.Label(self.enter_frame, textvariable=self.error_checker, bg='LightBlue').grid(row=1, column=2, columnspan=2, sticky='n')

        # =====REGULAR COLORS===== <--- UNFINISHED RAN INTO ERROR FIRST

        tk.Label(self.enter_frame, text='Color:', bg='LightBlue').grid(row=2, column=2, sticky='n')

        self.reg_color = tk.Entry(self.enter_frame, width=50)
        self.reg_color.grid(row=2, column=3, sticky='n')



    def change_color_hex(self):
        if hexa_checker_regex.search(self.the_color_hex.get()) is None:
            self.error_checker.set('That is an invalid hexadecimal value!')
        else:
            try:
                self.color.configure(bg=self.the_color.get())
                self.error_checker.set('')
            except:
                self.error_checker.set('That is an invalid hexadecimal value!')
        self.the_color_hex.delete(0, 'end')



root = tk.Tk()
error_checker = tk.StringVar()
app = Window(root, error_checker)
root.mainloop()

Looks Like

那么,为什么条目和按钮不在框架中。另外,如果条目和按钮在框中,为什么它们的位置会受到框的影响(不是因为框的背景是红色的)?

1 个答案:

答案 0 :(得分:4)

问题是这条线

self.enter_frame = tk.Frame(self.master, bg='Red').grid(row=0, column=2, sticky='n')

self.enter_frame将等于“ None”,因此tkinter不能使用它来放置其他小部件。更改为

 self.enter_frame = tk.Frame(self.master, bg='Red')
 self.enter_frame.grid(row=0, column=2, sticky='n')

,您的一些问题将消失。

另一个错误是这一行

self.color.configure(bg=self.the_color.get())

应该是

self.color.configure(bg=self.the_color_hex.get())