问题描述
我有一个代码,我在其中尝试不同的 Tkinter 小部件,但 Colab 发回一个错误,指出没有显示名称或变量.确切的错误消息如下所示:
I have a code where I'm trying out different Tkinter widgets, but Colab sends back an error saying that there's no display name or variable. The exact error message looks something like what follows:
TclError Traceback (most recent call last)
<ipython-input-5-7b43f8be599d> in <module>()
----> 1 form = tk.Tk()
/usr/lib/python3.6/tkinter/__init__.py in __init__(self, screenName, baseName, className, useTk, sync, use)
2021 baseName = baseName + ext
2022 interactive = 0
-> 2023 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
2024 if useTk:
2025 self._loadtk()
TclError: no display name and no $DISPLAY environment variable
有什么办法可以解决这个问题吗?代码是这样的:
Is there any way to work around this? The code goes something like this:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
def fOpen():
print(filedialog.askopenfilename(initialdir = "/",title = "Open file",filetypes = (("Python files","*.py;*.pyw"),("All files","*.*"))))
def ExitF():
form.destroy()
def fSave():
print(filedialog.asksaveasfilename(initialdir = "/",title = "Save as",filetypes = (("Python files","*.py;*.pyw"),("All files","*.*"))))
form = tk.Tk()
form.title("Colab Form")
menubar = tk.Menu(form)
filemenu = tk.Menu(menubar,tearoff=0)
filemenu.add_command(label="Open", command = fOpen)
filemenu.add_command(label="Save", command = fSave)
filemenu.add_command(label="Exit", command = ExitF)
menubar.add_cascade(label="File", menu=filemenu)
form.config(menu=menubar)
#Listbox with attached scrollbar
scrollbar=tk.Scrollbar(form)
mylist = tk.Listbox(form, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert("end", "This is line number " + str(line))
mylist.grid(row=7,column=1,rowspan=3, sticky='e', padx=25, pady=25)
scrollbar.config( command = mylist.yview )
scrollbar.grid(row=7, column=2, rowspan=3, sticky='nsw', padx=25, pady=25)
form.mainloop()
推荐答案
As 运行健身房-Google Colaboratory 上的 -gazebo 说,您需要运行一个帧缓冲服务器(它将模拟图形屏幕)并创建一个指向它的 DISPLAY
envvar.
As Run gym-gazebo on Google Colaboratory says, you need to run a framebuffer server (that will emulate a graphical screen) and create a DISPLAY
envvar pointing to it.
!apt-get install -y xvfb # Install X Virtual Frame Buffer
import os
os.system('Xvfb :1 -screen 0 1600x1200x16 &') # create virtual display with size 1600x1200 and 16 bit color. Color can be changed to 24 or 8
os.environ['DISPLAY']=':1.0' # tell X clients to use our virtual DISPLAY :1.0
但是,如果您想与 GUI 交互,那将会很困难,因为 Colab 不支持开箱即用的交互式屏幕.
However, if you want to interact with the GUI, that's going to be hard, 'cuz Colab doesn't support interactive screens out of the box.
这篇关于有没有办法将 Tkinter 与 Google Colaboratory 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!