如何用Tkinter按钮更新窗口的背景色

2024-04-29 15:54:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试正确的代码,采取一个随机的十六进制数字,转换为RGB,并显示在一个窗口。我还想要一个能改变颜色的按钮。目前,除了按钮没有改变窗口的颜色外,其他一切都正常,即使生成了一个新的十六进制数。我试着打开一个新窗口,每按一个按钮就创建一个更新,没有运气。这是我的密码。在

import tkinter as tk
import random

options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
r1 =random.choice(options)
r2 =random.choice(options)
r3 =random.choice(options)
r4 =random.choice(options)
r5 =random.choice(options)
r6 =random.choice(options)
hexnumber = '#' +r1 + r2 + r3 + r4 +r5 + r6

def ChangeHex():
    options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',  'D', 'E', 'F']
    r1 =random.choice(options)
    r2 =random.choice(options)
    r3 =random.choice(options)
    r4 =random.choice(options)
    r5 =random.choice(options)
    r6 =random.choice(options)
    hexnumber = '#' +r1 + r2 + r3 + r4 +r5 + r6

def New():
    new = tk.Tk()
    new.geometry("800x800")
    new.resizable(0, 0)
    new.configure(bg=hexnumber)
    b = tk.Button(new, text="Change Your Color",command=Combine)
    b.pack()
    new.mainloop()

def ChangeColor():
    root.config(bg = hexnumber)

def Combine():
    ChangeHex()
    ChangeColor()

root = tk.Tk()
root.geometry("800x800")
root.resizable(0, 0)
root.configure(bg=hexnumber)
b = tk.Button(root, text="Change Your Color",command=Combine)
b.pack()
root.mainloop()

另外,抱歉,如果这是愚蠢的,这是我第一次使用tkinter。在


Tags: newdefrandomroot按钮tkoptionsr2
1条回答
网友
1楼 · 发布于 2024-04-29 15:54:16

有两个名为hexnumber的变量

  • 第一个-全局-创建外部函数

  • 第二个-local-在ChangeHex()

必须使用ChangeHex()中的global hexnumber通知函数,而不是使用外部全局变量,而不是创建局部变量

def ChangeHex():
    global hexnumber

    options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',  'D', 'E', 'F']
    r1 =random.choice(options)
    r2 =random.choice(options)
    r3 =random.choice(options)
    r4 =random.choice(options)
    r5 =random.choice(options)
    r6 =random.choice(options)
    hexnumber = '#' +r1 + r2 + r3 + r4 +r5 + r6

但如果使用return hexnumber并使用参数-def ChangeColor(hexnumber):运行函数,效果会更好

^{pr2}$

相关问题 更多 >