首页 > 解决方案 > Python:无法将文件拆分为多个文件

问题描述

我有一个游戏项目,其中有我的服务器和客户端。我想拆分我的客户端和服务器,这样更容易阅读。

我将所有配置 tkinter 窗口放在一个文件中,然后放入服务器中from window import *

start_server()但是在 windows 文件中,我正在调用客户端中的一个函数,当我启动客户端时它无法识别该函数。

有什么建议我该怎么做?谢谢你的帮助 !

服务器.py

import socket
import threading
from time import sleep
from window import *

def start_server():
    global server, HOST_ADDR, HOST_PORT  # code is fine without this
    btnStart.config(state=tk.DISABLED)
    btnStop.config(state=tk.NORMAL)
(...)

窗口.py

import tkinter as tk

window = tk.Tk()
window.title("Tic-Tac-Toe Server")
window.iconbitmap("logo.ico")
window.config(background='#4065A4')

# Top frame consisting of two buttons widgets (i.e. btnStart, btnStop)
topFrame = tk.Frame(window)
btnStart = tk.Button(topFrame, text="Start", font=("Helvetica", 20), bg='#4065A4', fg='white',
                     command=lambda : start_server())
btnStart.pack(side=tk.LEFT)
btnStop = tk.Button(topFrame, text="Stop", font=("Helvetica", 20), bg='#4065A4', fg='white', command=lambda : stop_server(), state=tk.DISABLED)
btnStop.pack(side=tk.LEFT)
topFrame.pack(side=tk.TOP, pady=(5, 0))

# Middle frame consisting of two labels for displaying the host and port info
middleFrame = tk.Frame(window)
lblHost = tk.Label(middleFrame, font=("Helvetica", 10), bg='#4065A4', fg='white', text = "Address: X.X.X.X")
lblHost.pack(side=tk.LEFT)
lblPort = tk.Label(middleFrame, font=("Helvetica", 10), bg='#4065A4', fg='white', text = "Port:XXXX")
lblPort.pack(side=tk.LEFT)
middleFrame.pack(side=tk.TOP, pady=(5, 0))

# The client frame shows the client area
clientFrame = tk.Frame(window)
lblLine = tk.Label(clientFrame,  font=("Helvetica"), text="Liste des joueurs").pack()
scrollBar = tk.Scrollbar(clientFrame)
scrollBar.pack(side=tk.RIGHT, fill=tk.Y)
tkDisplay = tk.Text(clientFrame, height=10, width=30)
tkDisplay.pack(side=tk.LEFT, fill=tk.Y, padx=(5, 0))
scrollBar.config(command=tkDisplay.yview)
tkDisplay.config(yscrollcommand=scrollBar.set, background="#F4F6F7", highlightbackground="grey", state="disabled")
clientFrame.pack(side=tk.BOTTOM, pady=(5, 10))

标签: pythonfileimport

解决方案


window导入后在 server.py 中绑定/配置回调。

窗口.py

...
btnStart = tk.Button(topFrame, text="Start", font=("Helvetica", 20), bg='#4065A4', fg='white')
...

服务器.py

...
from window import *
btnStart.configure(command=lambda : start_server())
...

设置选项


推荐阅读