使用Python Tkinter模块进行编码时遇到问题

时间:2020-08-20 05:33:48

标签: python tkinter

最近,我在使用Python Tkinter模块进行编码时遇到问题。

该项目是一个URL缩短器。

(I was not allowed to post actual photo out here yet) Click here to see the picture that illustrated how my project looks.

这是我写的代码:

import tkinter as tk
import random 
import string

def shorten_url():
    url = url_input_space_entry.get()
    result_url_random_part = ''.join(random.choice(string.hexdigits) for digit in range(6))
    result_url = f"www.urlshort.com/{result_url_random_part}"
    show_result.configure(text=result_url)

window = tk.Tk()
window.title("URL Shortener")
window.geometry("700x600")

app_title = tk.Label(window, text="URL Shortener")
app_title.pack()

url_input_space = tk.Frame(window)
url_input_space.pack()
url_input_label = tk.Label(url_input_space, text="Please enter your URL: ")
url_input_label.pack(side=tk.LEFT)
url_input_space_entry = tk.Entry(url_input_space, width=45)
url_input_space_entry.pack()

result_frame = tk.Frame(window)
result_frame.pack()
result_label = tk.Label(result_frame, text="Result: ")
result_label.pack(side=tk.LEFT)
show_result = tk.Entry(result_frame, width=34)
show_result.pack()

shorten_url_button = tk.Button(window, text="Shorten it", command=shorten_url)
shorten_url_button.pack()

window.mainloop()

所以,我希望:

首先,我输入需要缩短的URL:

请输入您的URL:xxxx.com(示例URL)

然后,在我按下“ Shorten it”按钮之后,这就是我希望进入结果框架的结果:

结果:www.urlshort.com/XXXXXX(随机的6位数字和字母,例如9eDS34,A1e2wS等)

但是现在,按下按钮后,RESULT框什么也没有显示。 (之所以对这个问题一无所知,是因为在我运行程序之后,没有出现错误消息。)

有人可以告诉我我写错了什么,如何解决?非常感谢!

1 个答案:

答案 0 :(得分:2)

您不能将配置方法与Entry小部件一起使用。 相反,您应该清除Entry,然后像这样插入您的字符串:

show_result.delete(0, tk.END)
show_result.insert(0,result_url)

您的主要代码应为

def shorten_url():
    url = url_input_space_entry.get()
    result_url_random_part = ''.join(random.choice(string.hexdigits) for digit in range(6))
    result_url = f"www.urlshort.com/{result_url_random_part}"
    show_result.delete(0, tk.END)
    show_result.insert(0,result_url)

window = tk.Tk()
window.title("URL Shortener")
window.geometry("700x600")

app_title = tk.Label(window, text="URL Shortener")
app_title.pack()

url_input_space = tk.Frame(window)
url_input_space.pack()
url_input_label = tk.Label(url_input_space, text="Please enter your URL: ")
url_input_label.pack(side=tk.LEFT)
url_input_space_entry = tk.Entry(url_input_space, width=45)
url_input_space_entry.pack()

result_frame = tk.Frame(window)
result_frame.pack()
result_label = tk.Label(result_frame, text="Result: ")
result_label.pack(side=tk.LEFT)
show_result = tk.Entry(result_frame, width=34)
show_result.pack()

shorten_url_button = tk.Button(window, text="Shorten it", command=shorten_url)
shorten_url_button.pack()

window.mainloop()