root = tkinter.Tk() #聊天主窗口 root.title(user) #用户名为窗口标题 root['height'] = 400 root['width'] =580 root.resizable(0,0)我想在这个基础上增加一个页面出现的位置
时间: 2024-02-02 07:03:42 浏览: 18
可以使用`geometry`方法来设置页面出现的位置。例如,如果你想将窗口显示在屏幕中央,可以使用以下代码:
```
import tkinter as tk
# 创建窗口并设置属性
root = tk.Tk()
root.title(user)
root.geometry('580x400+{}+{}'.format((root.winfo_screenwidth() - 580) // 2, (root.winfo_screenheight() - 400) // 2))
root.resizable(True, True)
```
其中,`geometry`方法的第二个参数`'+{}+{}'`表示设置窗口的位置,第一个`{}`表示窗口左上角的横坐标,第二个`{}`表示窗口左上角的纵坐标。在这个例子中,`580`和`400`是窗口的宽度和高度,`(root.winfo_screenwidth() - 580) // 2`和`(root.winfo_screenheight() - 400) // 2`分别是窗口左上角的横坐标和纵坐标,可以将窗口显示在屏幕正中央。
相关问题
我想把root = tkinter.Tk() #聊天主窗口 root.title(user) #用户名为窗口标题 root['height'] = 400 root['width'] =580 root.resizable(0,0)代码改成位于屏幕中央,并且可调节窗口大小
可以使用以下代码来实现:
```
import tkinter as tk
# 获取屏幕宽度和高度
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# 计算窗口宽度和高度
window_width = 580
window_height = 400
# 计算窗口左上角坐标
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
# 创建窗口并设置属性
root = tk.Tk()
root.title(user)
root.geometry('{}x{}+{}+{}'.format(window_width, window_height, x, y))
root.resizable(True, True)
```
这段代码使用了`tkinter`库中的`geometry`方法来设置窗口的大小和位置,`resizable`方法来设置窗口是否可调节大小。其中,`window_width`和`window_height`是窗口的宽度和高度,`x`和`y`是窗口左上角的坐标,这些参数可以根据需要进行调整。
root = tkinter.Tk() # 聊天主窗口 root.title(user) # 用户名为窗口标题 root['height'] = 400 root['width'] = 710 root.resizable(0, 0) # 创建滚动文本框 chatbox = ScrolledText(root, font=("黑体", 16)) chatbox.place(x=5, y=0, width=570, height=320) chatbox.tag_config('red', foreground='red') chatbox.tag_config('blue', foreground='blue') chatbox.tag_config('green', foreground='green') chatbox.tag_config('black', foreground='black') chatbox.insert(tkinter.END, '欢迎来到图灵聊天室!','blue') 在这个代码基础上添加一个”添加好友“的按钮,并跳转到好友添加界面
可以使用 tkinter 中的 Button 组件来创建一个“添加好友”按钮,并为其绑定一个函数,实现跳转到好友添加界面。
以下是示例代码:
```
import tkinter
from tkinter.scrolledtext import ScrolledText
def add_friend():
# 跳转到好友添加界面的代码
root = tkinter.Tk()
root.title(user)
root['height'] = 400
root['width'] = 710
root.resizable(0, 0)
chatbox = ScrolledText(root, font=("黑体", 16))
chatbox.place(x=5, y=0, width=570, height=320)
chatbox.tag_config('red', foreground='red')
chatbox.tag_config('blue', foreground='blue')
chatbox.tag_config('green', foreground='green')
chatbox.tag_config('black', foreground='black')
chatbox.insert(tkinter.END, '欢迎来到图灵聊天室!','blue')
add_button = tkinter.Button(root, text="添加好友", font=("黑体", 14), command=add_friend)
add_button.place(x=600, y=50, width=100, height=40)
root.mainloop()
```
在上面的代码中,我们创建了一个名为 `add_friend` 的函数,并将其绑定到了一个名为 `add_button` 的按钮上。在这个函数中,你可以编写跳转到好友添加界面的代码。在主窗口中,我们使用了 `Button` 组件来创建了一个按钮,并将其放置在了主窗口上,通过设置 `command` 参数为 `add_friend` 函数,实现了点击按钮时调用该函数。