“TypeError: Can't convert 'NoneType' object to str implicitly” when var should have a value

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

import sys from tkinter import * def print():     print("Encoded " + message + " with " + offset)  gui = Tk()  gui.title("Caesar Cypher Encoder")  Button(gui, text="Encode", command=encode).grid(row = 2, column = 2) Label(gui, text = "Message").grid(row = 1, column =0) Label(gui, text = "Offset").grid(row = 1, column =1) message = Entry(gui).grid(row=2, column=0) offset = Scale(gui, from_=0, to=25).grid(row=2, column=1)  mainloop( ) 

When i run this code with an input in both the input box and a value on the slider - it comes up with the error

>>>Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) File "C:/Users/xxxx/Desktop/Code/Functionised/GUI.pyw", line 5, in encode print("Encoded " + message + " with " + offset) TypeError: Can't convert 'NoneType' object to str implicitly 

using a simple str() does not work by the way

EDIT

With the new code

import sys from tkinter import * def printer():     print(message)     print(offset)  gui = Tk()  gui.title("Caesar Cypher Encoder")  Button(gui, text="Encode", command=printer).grid(row = 2, column = 2) Label(gui, text = "Message").grid(row = 1, column =0) Label(gui, text = "Offset").grid(row = 1, column =1) message = Entry(gui) message.grid(row=2, column=0) offset = Scale(gui, from_=0, to=25) offset.grid(row=2, column=1)  mainloop( ) 

It returns

.46329264 .46329296 

EDIT 2

def printer():     print(message.get())     print(offset.get()) 

this fixes the .xxxxxxxx problem

回答1:

In answer to your first edit - the .get() command should be the most useful

Use it in the form of

print(message.get()) 

rather than

print(message) 


回答2:

You are setting the variables message and offset to widgets but then you position them on the same line, this makes them Nonetype objects, instead position them on the next line e.g.:

message = Entry(gui) message.grid(row=2, column=0) offset = Scale(gui, from_=0, to=25) offset.grid(row=2, column=1) 

this should solve your problem, but also, it's not advised to use from tkinter import * rather import tkinter as tk, and your function print() should be differently named (not the same as a python keyword) so that it is less confusing and prevents errors, make it printer() or similar to be on the safe side.

Hope this helps you!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!