所以问题来了。我开始使用python有一段时间了,遇到了一个问题。虽然一开始看起来很基本,但它让我忙了好几个小时。 *运行程序时我没有收到任何语法错误,尽管程序无法将新的IP写入文件。在
我正在为一个程序做一个函数,它要求客户机提供一个新的IP地址,因为服务器(我的IP)目前不是静态的。由于我的IP更改非常频繁,我希望给客户机(正在尝试与我建立连接)更改他们尝试连接的IP的选项。在
函数如下:
#CONFIGURE NEW IP
def IpConfigNew():
#Creates new window
IpConfig = Tk()
IpConfig.configure(background = 'white')
IpConfig.title('Configure IP')
IpConfig.geometry('300x60+260+380')
IpNew = StringVar()
Label(IpConfig, font = ('Helvetica',12), text = 'Please enter the IP address of the server', bg = 'white').place(x=0,y=4)
#Creates box for user to type IP in.
Entry(IpConfig,textvariable=IpNew, bg = "light blue").place(x=4,y=35)
#Store New Ip NOTE that it is nested within IpConfigNew
def IpStore():
#Retrieves new IP from text box and stores it in variable
GetIpNew = IpNew.get()
mypath = str('Latest Server')
#Creates directory to write new IP to.
if not os.path.isdir(mypath):
os.makedirs(mypath)
StoreLatestServer = open('Latest Server\NewIp.txt', 'w')
#Writes new IP
StoreLatestServer.write("%s"%(GetIpNew))
StoreLatestServer.close()
IpConfig.destroy()#Closes window
#Calls on function IpStore in order to store the new IP
Button(IpConfig,text = 'Done', command = IpStore).place(x=150,y=30)
IpConfig.mainloop()
def PromptIpReconfig():
confirm = tkMessageBox.askyesno(title = "Configure Server IP", message = "Are you sure?")
#Checks to see if the user chose to change IP
if confirm >0:
#In the event that the user said yes go to IpConfigNew
IpConfigNew()
else:
return
#Configure Menu Bar #Sets up Menu Bar for parent Window(app)
menubar = Menu(app)
filemenu = Menu(menubar,tearoff = 0)
# Goes to PromptIpReconfig (Prompts user to Reconfigure the IP after clicking button)
filemenu.add_command(label="Configure IP", command = PromptIpReconfig)
filemenu.add_command(label="Quit", command=app.destroy)
menubar.add_cascade(label='Options',menu = filemenu)
app.config(menu=menubar)#Draws menubar on parent window(app)
我不知道为什么它不起作用,因为我以前做过这件事,期望稍有不同。尝试写入新文件时,我尝试写入新文件。新目录被创建了,所以我知道该函数正在工作。我对比了我之前制作的程序和这个程序。 我发现,如果我这样做,效果很好:
^{pr2}$我发现,如果我不使用菜单栏启动,而是在程序启动时启动它,它工作得很好。我不确定问题是从菜单栏调用ipconfig函数,还是与我正在嵌套函数有关。在
如果有人能帮我出去,我会很高兴的,因为它已经困扰了我好几天了!在
我将把这两行移到
IpConfigNew
的末尾:编辑:似乎存在一种具有多个事件循环和 StringVar,请参见Tkinter Folklore。无论如何,在你的情况下,你想显示一个对话,你 不需要另一个Tk循环。因此,请这样更改代码:
^{pr2}$这在我的测试中解决了你的问题。在
我事先没有把我的计划安排得很清楚,我现在就试着解释一下。在
我所拥有的是我的主窗口,在我的主窗口(称为“应用程序”)中,我设置了一个菜单栏。此菜单栏有一个称为“选项”的级联和一个名为“PromptPreConfig”的命令:
当我调用函数“promptPreConfig”时,会发生以下情况:
^{pr2}$如果用户决定说“是”,则调用
IpConfigNew()
:ipconfig在主窗口中打开子窗口
IpConfig = Tk()
。子窗口提供了一个在输入新IP后单击的按钮。单击按钮后,它将调用命令“IpStore”:基本上,我的程序总体布局如下:
我很确定问题出在ipconfig函数上,因为这似乎是有效的:
这会让你们更清楚地了解我在处理什么。 谢谢
相关问题 更多 >
编程相关推荐