gpt4 book ai didi

python - 如何制作 tkinter 条目小部件?

转载 作者:行者123 更新时间:2023-12-01 05:43:23 25 4
gpt4 key购买 nike

这是我的代码:

import random
from tkinter import *
root=Tk()
a=Canvas(root, width=1000, height=1000)
a.pack()
e = Entry(root)
paralist = []
x=random.randint(1,10)
file = open("groupproject.txt")
line = file.readline()
for line in file:
paralist.append(line.replace("\n", ""));

a.create_text(500,50, text = "Typing Fun", width = 700, font = "Verdana", fill = "purple")
a.create_text(500,300, text = paralist[x], width = 700, font = "Times", fill = "purple")

#master = Tk()
#a = Entry(master)
#a.pack()
#a.focus_set()
#def callback():
# print (a.get())


root.mainloop()

注释部分应该在段落下方打印一个条目小部件,但它在 a.create_text(500,300, text = paralist) 行中给出错误 IndexError: list index out of range [x],宽度= 700,字体=“时代”,填充=“紫色”)。如果我使用 e 而不是 a 它可以工作,但会在单独的窗口中打开条目小部件。

我正在尝试使 tkinter 输入小部件与文本显示在同一窗口中。有人可以告诉我该怎么做吗?

最佳答案

首先,

paralist = []该列表为空,因此 1 到 10 之间的随机单词将是错误的,因为列表中没有任何内容。

master = Tk() # since Tk() is already assigned to root this will make a new window
a = Entry(master) # a is already assigned to canvas
a.pack() # this is already declare under a=canvas
a.focus_set()
def callback():
print (a.get())

编辑:

我怀疑您的文件可能有问题。这段代码:

import random
from tkinter import *

root = Tk()

a = Canvas(root, width = 400, height = 400)
a.pack()
e = Entry(root)
e.pack()

paralist = []

x = random.randint(1,10)

file = open("teste.txt")
line = file.readline()

for line in file:
paralist.append(line.replace("\n", ""));

a.create_text(200,50, text = "Typing Fun", width = 700, font = "Verdana", fill = "purple")
a.create_text(200,300, text = paralist[x], width = 700, font = "Times", fill = "purple")

b = Entry(root)
b.pack()
b.focus_set()

def callback():
print (a.get())

root.mainloop()

将此作为“teste.txt”:

test0
test1
test2
test3
test4
test5
test6
test7
test8
test9
test10

对我来说效果很好。

关于python - 如何制作 tkinter 条目小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16877666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com