我正在使用 tkinter 制作一个 GUI,它允许我单击一个按钮来运行端口扫描。我有一个功能正常的端口扫描脚本,我已设法通过 GUI 上的按钮打开端口扫描仪,但随后我收到一个错误,否则单独运行端口扫描仪时不会收到该错误。
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Steve\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "<string>", line 51, in Scan
NameError: name 'IP_Input' is not defined
我的代码:
class CallWrapper:
"""Internal class. Stores function to call when some user
defined Tcl function is called e.g. after an event occurred."""
def __init__(self, func, subst, widget):
"""Store FUNC, SUBST and WIDGET as members."""
self.func = func
self.subst = subst
self.widget = widget
def __call__(self, *args):
"""Apply first function SUBST to arguments, than FUNC."""
try:
if self.subst:
args = self.subst(*args)
return self.func(*args) # THIS IS THE ERROR #
except SystemExit:
raise
except:
self.widget._report_exception()
class XView:
"""Mix-in class for querying and changing the horizontal position
of a widget's window."""
def xview(self, *args):
"""Query and change the horizontal position of the view."""
res = self.tk.call(self._w, 'xview', *args)
这是第 51 行错误的代码
def Scan():
print ('Scan Called.') #Debugging
IP = str(IP_Input.get(0.0, tkinter.END)) #THIS IS ERROR LINE 51#
print ("IP #Debugging")
Start = int(PortS.get(0.0, tkinter.END))
End = int(PortE.get(0.0, tkinter.END))
TestSocket = socket.socket()
CurrentPort = Start
OpenPorts = 0
print ('Starting scan...')
HowFar = int(CurrentPort/End * 100)
ProgText = HowFar, r'%'
Label1.config(text=('Percentage Done:', ProgText))
最佳答案
问题出在您的 exec
语句上。您正在打开另一个名为 port_scanner.py
的 .py
文件,然后调用 exec(open("./port Scanner.py))
.
这根本行不通。
为什么这不起作用:
当你执行exec(open("path to .py file").read())
时,exec当然会执行这段代码,但问题是这个文件中的全局变量不是不在范围内。
所以,要使这项工作(我不推荐)你必须使用:
exec(open(path).read(), globals())
If the globals dictionary does not contain a value for the key builtins, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own builtins dictionary into globals before passing it to exec().
如果您确实想以这种方式调用文件,那么您应该使用os.system
。
替代方法:
您确实不需要以这种方式调用您的文件。您现在有两个正在运行的 Tk()
实例。如果您需要另一个窗口,则为此目的提供了一个小部件。它是Toplevel
小部件。您可以重构代码以创建一个 Toplevel
实例,其中包含单击按钮时的端口扫描器应用程序。一个例子是,使用顶级小部件创建端口扫描器应用程序(如果您愿意,可以在您的其他文件中),然后将“应用程序”导入到您的文件中,然后单击按钮使其初始化应用程序。
附加说明:
您正在调用 while
循环,如果它运行(任何明显的时间),那么这将阻止 GUI 的主事件循环并导致 GUI “挂起”。
您的第一个猜测不应该是广泛测试和使用的Python标准库的一部分存在缺陷。问题是(99.9% 的时间)
while True:
print("In your own code.")
关于python - 带有打开端口扫描器按钮的 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37351871/