简体   繁体   English

Python如何将用户提供的IP地址写入文件?

[英]Python How do I write a user provided IP address to a file?

so here's the problem. 这就是问题所在。 I have started using python for a little while and I have come across a problem. 我已经开始使用python了一段时间,但遇到了一个问题。 Although it may seem basic at first, it has had me busy for hours on end. 尽管乍一看似乎很基础,但最后却让我忙了几个小时。 *I do not receive any syntax errors when running the program, although the program fails to write the new IP to file. *尽管程序无法将新IP写入文件,但运行程序时我没有收到任何语法错误。

I am making a function for a program, that asks the client for a new IP address as the servers(my IP) is currently not static. 我正在为程序创建函数,该函数要求客户端提供新的IP地址,因为服务器(我的IP)当前不是静态的。 As my IP changes quite frequently, i would like to give clients (that are attempting to establish a connection with me) the option to change the IP that they are trying to connect to. 由于我的IP更改非常频繁,因此我想为客户端(尝试与我建立连接)提供选项,以更改他们尝试连接的IP。

So here is the function: 所以这是函数:

#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)

I am not sure why its not working as I have done this before expect slightly differently. 我不确定为什么它不起作用,因为我之前所做的期望略有不同。 When I attempt to write the new IP to file, nothing gets written to the file. 当我尝试将新IP写入文件时,没有任何内容写入文件。 The new directory is created, so I know that the function is working. 新目录已创建,因此我知道该功能正在工作。 I contrasted between the program that I made a while back that work and this one. 我对比了前段时间编写的程序和该程序。 What i found was that if I did this it worked fine: 我发现的是,如果执行此操作,效果很好:

#CONFIGURE NEW IP
#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
 def IpStore():
     #Retrieves new IP from text box and stores it in variable GetIpNew
     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()
     #Closes window
     IpConfig.destroy()

#Calls on function IpStore in order to store the new IP
Button(IpConfig,text = 'Done', command = IpStore).place(x=150,y=30)
IpConfig.mainloop()

I found that if I initiate without using the menu bar and instead just initiate it at program start, it works fine. 我发现,如果我不使用菜单栏就启动,而只是在程序启动时启动它,它就可以正常工作。 I am not sure whether the problem is calling the IpConfigNew function from the menu bar or whether it has something to do with the fact that I am nesting functions. 我不确定问题是从菜单栏中调用IpConfigNew函数还是与我嵌套函数有关。

I would love it if someone could help me out here as its been bugging me for days! 如果有人可以在这里困扰我好几天了,我会喜欢的!

I would move those 2 lines inside IpConfigNew , at the end: 我将在IpConfigNew内部将这两行移动到最后:

#Calls on function IpStore in order to store the new IP    
Button(IpConfig,text = 'Done', command = IpStore).place(x=150,y=30)
IpConfig.mainloop()

EDIT : it seems there is a kind of bug with multiple event loops and StringVar, see Tkinter Folklore . 编辑 :似乎有一个带有多个事件循环和StringVar的错误,请参阅Tkinter Folklore Anyway in your case you want to show a dialog, you don't need another Tk loop. 无论如何,要显示一个对话框,都不需要另一个Tk循环。 So change your code like this: 因此,像这样更改代码:

def IpConfigNew():
    #Creates a Toplevel window instead of a new "main" window in a new loop
    IpConfig = Toplevel(app) 

    ...

    #IpConfig.mainloop()
    app.wait_window(IpConfig)

This solves your problem in my test. 这在我的测试中解决了您的问题。

I didnt make the layout of my program very clear beforehand, I will try and explain it now. 我没有事先弄清楚程序的布局,现在我将尝试进行解释。

What i have is my main window and inside my main window(called "app") i have set up a menu bar. 我所拥有的是我的主窗口,并且在我的主窗口(称为“ app”)内,我已经设置了一个菜单栏。 This menu bar has aa cascade called "options" and a command called "PromptIpReconfig": 该菜单栏具有一个称为“选项”的级联和一个名为“ PromptIpReconfig”的命令:

app = Tk() 
filemenu.add_command(label="Configure IP", command = PromptIpReconfig)
filemenu.add_command(label="Quit", command=app.destroy)
menubar.add_cascade(label='Options',menu = filemenu)

When I call the function "PromptIpReconfig" the following happens: 当我调用函数“ PromptIpReconfig”时,会发生以下情况:

def PromptIpReconfig():
   confirm = tkMessageBox.askyesno(title = "Configure Server IP", message = "Are you sure?")
   if confirm >0:
      IpConfigNew()
   else:
      return

If the user decides to say yes then IpConfigNew() is called: 如果用户决定说是,则调用IpConfigNew()

#CONFIGURE NEW IP
def IpConfigNew():
    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)
    Entry(IpConfig,textvariable=IpNew, bg = "light blue").place(x=4,y=35)

    #Store New Ip
    def IpStore():
        GetIpNew = IpNew.get()
        mypath = str('Latest Server')
        if not os.path.isdir(mypath):
            os.makedirs(mypath)
        StoreLatestServer = open('Latest Server\NewIp.txt', 'w')
        StoreLatestServer.write("%s"%(GetIpNew))
        StoreLatestServer.close()
        IpConfig.destroy()

    Button(IpConfig,text = 'Done', command = IpStore).place(x=150,y=30)
    IpConfig.mainloop()

IpConfigNew opens a child window IpConfig = Tk() within the main window. IpConfigNew在主窗口中打开一个子窗口IpConfig = Tk() The child window provides a button to click after the new IP has been entered. 子窗口提供输入新IP后单击的按钮。 Once the button is clicked it calls the command "IpStore": 单击按钮后,它将调用命令“ IpStore”:

#Store New Ip
def IpStore():
    GetIpNew = IpNew.get()
    mypath = str('Latest Server')
    if not os.path.isdir(mypath):
        os.makedirs(mypath)
    StoreLatestServer = open('Latest Server\NewIp.txt', 'w')
    StoreLatestServer.write("%s"%(GetIpNew))
    StoreLatestServer.close()
    IpConfig.destroy()

So basically the overall layout of my program looks like this: 因此,基本上我的程序的总体布局如下所示:

from Tkinter import *
import os
import tkMessageBox
#Create parent window
app = Tk()

def IpConfigNew():
   #Creates new window 
   IpConfig = Tk()
   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?")
   if confirm >0:
      #In the case that the user says yes
      IpConfigNew()
   else:
      return


#Create menu bar
filemenu.add_command(label="Configure IP", command = PromptIpReconfig)
filemenu.add_command(label="Quit", command=app.destroy)
menubar.add_cascade(label='Options',menu = filemenu)

app.mainloop()

I am pretty sure the problem is the function IpConfigNew as this seems to work: 我很确定问题出在函数IpConfigNew上,因为这似乎可行:

from Tkinter import *
import tkMessageBox
import os


#Creates new window   
IpConfig = Tk()
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()

This should give you guys a much clearer understanding of what I am dealing with. 这应该使你们对我正在处理的内容有了更清晰的了解。 Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python使用相同的IP地址在其他用户帐户中写入/删除/读取文件? - How can you write/delete/read a file in a different user account with the same ip address with python? 如何识别IP地址的用户类型? 使用python和requests / bs4 / flask - How do I identify the user type of an IP address? Using python and requests/bs4/flask 如何在 Django 中获取用户 IP 地址? - How do I get user IP address in Django? Python-如何将用户输入写入Excel文件? - Python- how do I write user input to an Excel file? 如何在python脚本中将IP地址从文本文件分配给主机名 - How do I assign IP address from text file to hostname in python script 如何从Python中的IP地址获取NAPTR记录? - How do I grab a NAPTR record from an IP address in Python? 如何从 python 中的以下元组中获取 IP 地址 - How do i fetch the IP address from the following tuple in python Python:如何从FQDN获取IP地址 - Python: How do I get the IP address from a FQDN 如何在 python 服务器上获取客户端 IP 地址 - How do i get the client ip address on a python server 如何编写一个程序来打印用户在 Python 中提供的大小为 m × n 的乘法表? - How can I write a program that prints a multiplication table of size m by n which is provided by the user in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM